import ENV_CONFIG from "@/config/env";
let apiUrl = ENV_CONFIG.BASE_API; //域名
// http://api-bbit.quannengshi.top:8080/https://api.quannengshi.top
import tools from '@/utils/tools';

function ajax(
	url,
	method,
	data,
	header,
	dataType
) {
	// console.log(url, data, method, header, dataType)
	data = data || {};
	data.mini_program = 1;
	let token = uni.getStorageSync('userInfo').token;
	let index = url.lastIndexOf("\/");
	let url_ = url.substring(index + 1, url.length);
	data['func'] = url_;
	data = tools.ident(data);
	console.log(data, "传递参数", url);
	data = JSON.stringify(data);
	data = tools.encrypt(data);
	// console.log(data, "加密")
	// let pass = '';
	// if (url == '/authentication') {
	// 	let {
	// 		username,
	// 		password
	// 	} = data;
	// 	pass = window.btoa(username + ':' + password);
	// }
	// uni.getStorageSync('userInfo') ? data.uid = uni.getStorageSync('userInfo').uid : data.uid = 1;//用户id
	// uni.getStorageSync('userInfo') ? data.organization_id = uni.getStorageSync('userInfo').organization_id : data.organization_id = 1;//用户组织id
	// console.log(data, "接口参数", apiUrl, url)
	return new Promise((resolve, reject) => {
		uni.request({
			url: apiUrl + url,
			method: method || "GET",
			// "content-type": "application/x-www-form-urlencoded",
			header: header || {
				'content-type': 'application/json',
				// 'content-type': "application/x-www-form-urlencoded",
				'Authorization': token ? `Bearer ${token}` : '',
			},
			timeout: 1800000,
			dataType: dataType || "json",
			data: data ? {
				data
			} : {},
			success(res) {
				// console.log(res, "AjX输出")
				if (res.statusCode == 401) {
					uni.setStorageSync('userInfo', '');
					uni.reLaunch({
						url: '/pages/block/block'
					})
					return;
				}
				if (res.statusCode == 404) {
					uni.showToast({
						icon: 'error',
						title: '接口不存在'
					})
					return;
				}
				if (res.statusCode == 405) {
					uni.showToast({
						icon: 'error',
						title: '接口请求方式错误'
					})
					return;
				}
				if (res.statusCode == 500) {
					uni.showToast({
						icon: 'error',
						title: '服务端错误'
					})
					return;
				}
				try {
					let data = res.data
					data = JSON.parse(tools.decode_h(data))
					resolve(data)
				} catch (error) {
					console.log(error, "解密错误")
					uni.showToast({
						title: '解密错误',
						icon: 'error'
					})
				}
			},
			fail(err) {
				uni.hideLoading();
				uni.showToast({
					title: '系统错误!',
					icon: 'none'
				})
				reject(err)
			},
			complete() {

			}
		})
	})
}
export default {
	ajax,
	apiUrl
}